//
//  GC_XMLParser.m
//  XMLtoCD04
//
//  Created by Miles on 10-03-23.
//  Copyright 2010 Miles Thorogood
//  greenmeat.net. All rights reserved.
//
/* Usage
 
 NSString *url = @"http://greenmeat.net/artistList3.xml" ;
 NSString *parentTag = @"ec_gradsubmission" ;
 NSArray *tags = [[[NSArray alloc] initWithObjects:@"last_name", @"first_name", @"program_type", @"medium", @"text", @"timestamp",@"filepath", nil] autorelease];
 NSMutableArray *artistsFromXML = [[GC_XMLParser alloc] initWithObjects:url parent:parentTag elements:tags] ;
 
 NSString *name = [[artistsFromXML objectAtIndex:artistIndex] objectForKey:@"last_name"] ;
 
 */
#import "GC_XMLParser.h"


@implementation GC_XMLParser

@synthesize parentElement ;
@synthesize workElements ;
@synthesize current ;
@synthesize currentElement ;
@synthesize elements, arrangedElementList ;
@synthesize parser ;
@synthesize item ;
@synthesize artists ;

- (id) initWithObjects:(NSString *)URL parent:(NSString *)inParent elements:(NSArray *)inElements {
	
	self = [super init] ;
	if (self) {
		//fileURL = URL ;
		self.parentElement = inParent ;
		self.workElements = [[NSArray alloc] initWithArray:inElements copyItems:YES] ;
	
	}
	[self parseXMLFileAtURL:URL] ;
	
	return artists ;
}


#pragma mark XML Parser methods
- (void) parseXMLFileAtURL:(NSString *)URL {
	
	self.artists = [[NSMutableArray alloc] init] ; // this will be the array we return
	
	NSURL *xmlURL = [NSURL URLWithString:URL] ;
	
	self.parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL] ;
	
	[self.parser setDelegate:self] ;
	[self.parser setShouldProcessNamespaces:NO ] ;
	[self.parser setShouldReportNamespacePrefixes:NO ] ;
	[self.parser setShouldResolveExternalEntities:NO ] ;
	
	[self.parser parse] ;
}

- (void)parserDidStartDocument:(NSXMLParser *)parser {
	//NSLog(@"found file and started parsing");
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
	NSString * errorString = [NSString stringWithFormat:@"Unable to download artists file (Error code %i )", [parseError code]];
	//NSLog(@"error parsing XML: %@", errorString);
	
	UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[errorAlert show];
	[errorAlert release] ;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
	self.currentElement = [elementName copy];
	if ([elementName isEqualToString:parentElement]) {
		// clear out our item caches...
		self.item = [[NSMutableDictionary alloc] init] ;
		self.elements = [[NSMutableArray alloc] init] ;
		self.arrangedElementList = [[NSMutableArray alloc] init] ;
	}
	
	for(NSString *str in self.workElements) {

		if ([self.currentElement isEqualToString:str]) {
			//NSLog(@"the found start element: %@", str) ;
			self.current = [[NSMutableString alloc] init];
			[arrangedElementList addObject:str] ;
		}
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

	for(NSString *str in self.workElements) {
		if ([self.currentElement isEqualToString:str]) {
			[current appendString:string] ;
			//NSLog(@"keeping: %@", current);
		}
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	//NSLog(@"ended element: %@", elementName);
	
	for(NSString *str in self.workElements) {
		if ([self.currentElement isEqualToString:str]) {
			NSString *saveString = [self stripNewlineWhitespace:current] ;
			[current appendString:saveString] ;
			[self.elements addObject:saveString] ;
		}
	}
	
	if ([elementName isEqualToString:self.parentElement]) {
		// save values to an item, then store that item into the array...

		int count = 0 ;
		for(NSString *str in self.arrangedElementList) {
			//NSLog(@"putting element into item: %@ == %@", str, [self.elements objectAtIndex:count] ) ;
			[self.item setObject:[self.elements objectAtIndex:count] forKey:str];
			count ++ ;
		}
		[self.artists addObject:[self.item copy]];	
	}
}


- (void)parserDidEndDocument:(NSXMLParser *)parser {
	
	//NSLog(@"DONE!");
	//NSLog(@"final array has %d items", [artists count]);
}

-(NSString *) stripNewlineWhitespace:(NSString *)string {
	NSCharacterSet *whitespaces = [NSCharacterSet whitespaceAndNewlineCharacterSet];
	NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
	NSArray *parts = [string componentsSeparatedByCharactersInSet:whitespaces];
	NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
	string = [filteredArray componentsJoinedByString:@" "];
	return string ;
}

- (void) dealloc {
	
	[parentElement release] ;
	[workElements release] ;
	[current release] ;
	[currentElement release] ;
	[elements release] ;
	[parser release] ;
	[item release] ;
	[artists release] ;
	
	[super dealloc] ;
}
@end
